<template>
  <div class="p-2.5">
    <!--优秀人员列表-->
    <template v-if="props.list">
      <template v-for="(item, index) in props.list" :key="index">
        <div
          v-if="!props.type || item.serviceType === props.type"
          class="mb-2.5 cursor-pointer active:opacity-80"
          @tap="viewUsers(item)"
        >
          <nut-card
            :img-url="item.photoPath"
            :title="item.name"
            :shop-desc="item.serviceType"
            :price="item.serviceFee.toString()"
          >
            <template #footer>
              <div class="flex justify-end gap-1.5">
                <nut-button @tap.stop="chat(item.id)">咨询</nut-button>
                <nut-button @tap.stop="booking(item.id, item.serviceType)">预约</nut-button>
              </div>
            </template>
          </nut-card>
        </div>
      </template>
    </template>

    <!--服务列表-->
    <template v-if="props.serverlist">
      <template v-for="(item, index) in props.serverlist" :key="index">
        <div
          v-if="(!props.type || item.type === props.type) && item.status === '待接单'"
          class="mb-2.5 cursor-pointer active:opacity-80"
          @tap="viewUsers(item)"
        >
          <div class="bg-white rounded-lg p-3 shadow-sm">
            <div class="mb-2">
              <div class="text-base font-medium text-gray-800 mb-1">{{ item.description }}</div>
              <div class="text-sm text-gray-600">{{ item.location }}</div>
            </div>
            <div class="my-2">
              <div class="flex items-center gap-2">
                <span class="text-sm text-blue-500 bg-blue-50 px-2 py-0.5 rounded">{{ item.type }}</span>
                <span class="text-xs text-gray-600 bg-gray-100 px-2 py-0.5 rounded">{{ item.status }}</span>
              </div>
            </div>
            <div class="flex justify-end mt-2">
              <nut-button @tap.stop="accrpt(item.id)">接受</nut-button>
            </div>
          </div>
        </div>
      </template>
    </template>
  </div>
</template>

<script setup lang="ts">
import { creatroom } from "@/api/customer";
import { usetakeserviceing } from "@/hooks/takeorders";
import { useBooking } from "@/hooks/usereservation";
import { ref } from "vue";

const { getcustomerbrowse } = useBooking();
const { takeserviceing } = usetakeserviceing();

const userId: number = uni.getStorageSync("userId");

// 定义一个接口来描述 list 中每个对象的结构
interface Employee {
  id: number;
  photoPath: string;
  name: string;
  serviceContent: string;
  serviceType: string;
  address: string;
  serviceFee: string;
}

interface serverList {
  id: number;
  businessOrderId: number;
  description: string;
  location: string;
  status: string;
  type: string;
  customerId: string;
  acceptedBy: string;
}
// 使用 defineProps 和 withDefaults 来定义 props 并设置默认值
const props = withDefaults(
  defineProps<{
    list?: Employee[];
    serverlist?: serverList[];
    type: string | undefined;
  }>(),
  {}
);

const emit = defineEmits(["updateList"]);

const viewUsers = (item: any) => {
  try {
    const encodedParams = encodeURIComponent(JSON.stringify(item));
    const usertype = uni.getStorageSync("usertype");

    if (usertype === "customer") {
      getcustomerbrowse(item.id);
      uni.navigateTo({
        url: `/pages/modules/user/employee/index?data=${encodedParams}`,
        fail: (err) => {
          console.error("跳转失败:", err);
        },
      });
    } else {
      uni.navigateTo({
        url: `/pages/modules/user/employee/xuqiu?data=${encodedParams}`,
        fail: (err) => {
          console.error("跳转失败:", err);
        },
      });
    }
  } catch (error) {
    console.error("处理跳转时发生错误:", error);
  }
};

const booking = (id: any, type: string) => {
  uni.navigateTo({
    url: `/pages/modules/user/release/index?servicePersonId=${id}&type=${type}`,
  });
};
const accrpt = async (id: number) => {
  try {
    const confirmed = await takeserviceing(id);
    // 只有在用户确认接单后才更新列表
    if (confirmed) {
      emit("updateList");
    }
  } catch (error) {
    console.error("接单失败:", error);
  }
};
const chat = async (id: number) => {
  const data = ref({
    customerId: userId,
    servicePersonId: id,
  });
  await creatroom(data.value).then((res: any) => {
    const chatData = {
      contact_id: id,
      conversation_id: res.data,
      service_person_name: props.list?.find((item) => item.id === id)?.name || "未知用户",
      avatar: props.list?.find((item) => item.id === id)?.photoPath || "",
    };
    console.log(chatData);

    uni.navigateTo({
      url: `/pages/chat/index?item=${encodeURIComponent(JSON.stringify(chatData))}`,
    });
  });
};
</script>

<style scoped>
:deep(.nut-card) {
  width: 100%;
  pointer-events: auto;
}
</style>
